package com.ilink.groundservice.controller;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ilink.groundservice.entity.PO.langflowApp.Download;
import com.ilink.groundservice.entity.PO.langflowApp.Like;
import com.ilink.groundservice.entity.VO.langflowApp.QueryConditionInfo;
import com.ilink.groundservice.entity.VO.langflowApp.UploadFlowInfo;
import com.ilink.groundservice.entity.VO.langflowApp.UserApiKeys;
import com.ilink.groundservice.entity.VO.langflowApp.UserApiKeysResponse;
import com.ilink.groundservice.service.LangflowAppService;
import com.ilink.ilinkcommon.domain.R;
import com.ilink.ilinkcommon.log.method.MethodLog;
import com.ilink.ilinkcommon.utils.UserContext;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <h3>new-ilink-java-backend</h3>
 *
 * @Description <p>应用广场-langflow版本</p>
 * @Author 30955
 * @Date 2024-09-19 18:21
 **/

@RestController
@RequiredArgsConstructor
@RequestMapping("/ground/langflow_app")
public class LangflowAppController {

    private final LangflowAppService langflowAppService;
    @Autowired
    private ObjectMapper objectMapper;

    @MethodLog(value = "检查应用广场服务状态")
    @GetMapping("/check/")
    public R check() {
        return R.ok(langflowAppService.check());
    }

    @MethodLog(value = "上传应用组件流程信息")
    @PostMapping("/components/upload")
    public R uploadFlow(@RequestBody UploadFlowInfo flowInfo) {
        return R.ok(langflowAppService.uploadFlow(flowInfo));
    }

    @MethodLog(value = "下载应用组件流程信息")
    @GetMapping("/components/download")
    public R downloadFlow(Download download) {
        return R.ok(langflowAppService.downloadFlow(download));
    }

    @MethodLog(value = "点赞或取消点赞应用组件流程")
    @PostMapping("/like")
    public R toggleLike(@RequestBody Like like) {
        return R.ok(langflowAppService.toggleLike(like));
    }

    @MethodLog(value = "获取所有应用组件流程信息")
    @GetMapping("/components/all")
    public R getAllFlows() {
        return R.ok(langflowAppService.getAllFlows());
    }


    @MethodLog(value = "获取chat应用组件流程信息")
    @GetMapping("/chat_flows")
    public R getChatFlows(@RequestParam (required = false)String flowId) {
        return R.ok(langflowAppService.getChatFlows(flowId));
    }

    @MethodLog(value = "更新应用组件流程信息")
    @PatchMapping("/components/update")
    public R updateFlow(@RequestBody UploadFlowInfo flowInfo) {
        return R.ok(langflowAppService.updateFlow(flowInfo));
    }

    @MethodLog(value = "根据条件查询应用组件流程信息")
    @GetMapping("/components/query")
    public R getFlowsByCondition(QueryConditionInfo condition) {
        return R.ok(langflowAppService.getFlowsByCondition(condition));
    }

    @MethodLog(value = "获取应用组件标签信息")
    @GetMapping("/tags")
    public R getTags() {
        return R.ok(langflowAppService.getTags());
    }

    @MethodLog(value = "获取用户文件夹信息")
    @GetMapping("/folders")
    public R getFolders() {
        String userId = UserContext.getUserId();
        return R.ok(langflowAppService.selectFolderByUserId(userId));
    }
    @MethodLog("在chat界面返回apikey")
    @GetMapping("/envs")
    public R getGroundLangflowAppEnvs(){
        String userId = UserContext.getUserId();
        try {
            List<UserApiKeys> userApiKeys = langflowAppService.getAllUserApiKeys(userId);
            List<UserApiKeysResponse> userApiKeysResponses = new ArrayList<>();
            for (UserApiKeys userApiKey : userApiKeys) {
                String fieldsData = userApiKey.getFieldsData();
                String dataName = userApiKey.getDataName();
                try {
                    Map<String, String> fieldsMap = objectMapper.readValue(fieldsData, new TypeReference<Map<String, String>>() {
                    });
                    for (Map.Entry<String, String> entry : fieldsMap.entrySet()) {
                        UserApiKeysResponse response = new UserApiKeysResponse();
                        response.setName(entry.getKey());
                        response.setValue(entry.getValue());
                        response.setDisplayName(dataName);
                        userApiKeysResponses.add(response);
                    }
                } catch (Exception e) {
                   return R.error("未获取到apikey，由于",e.getMessage());
                }
            }
            return R.ok("成功获取apikey",userApiKeysResponses);
        }
        catch (Exception e) {
            return R.error("未获取到apikey",e.getMessage());
        }

    }
}
